
const { ccclass, property } = cc._decorator;

@ccclass
export class Joystick extends cc.Component {

    @property(cc.Node)
    Joystick: cc.Node = null;

    Max_r: number = 100;


    public dir: cc.Vec2 = cc.v2(0, 0);

    onLoad() {
        this.Joystick.x = 0;
        this.Joystick.y = 0;
        this.dir = cc.v2(0, 0);

        this.Joystick.on(cc.Node.EventType.TOUCH_START, function (e) {
            var w_pos = e.getLocation();
            var pos = this.node.convertToNodeSpaceAR(w_pos);//将世界坐标转化为父节点的相对坐标

            var len = pos.mag();
            this.dir.x = pos.x / len;
            this.dir.y = pos.y / len;
            if (len > this.Max_r) {
                pos.x = this.Max_r * pos.x / len;
                pos.y = this.Max_r * pos.y / len;
            }
            this.Joystick.setPosition(pos);
        }, this);

        this.Joystick.on(cc.Node.EventType.TOUCH_MOVE, function (e) {
            var w_pos = e.getLocation();
            var pos = this.node.convertToNodeSpaceAR(w_pos);//将世界坐标转化为父节点的相对坐标


            var len = pos.mag();
            this.dir.x = pos.x / len;
            this.dir.y = pos.y / len;
            if (len > this.Max_r) {
                pos.x = this.Max_r * pos.x / len;
                pos.y = this.Max_r * pos.y / len;
            }
            this.Joystick.setPosition(pos);
        }, this);

        this.Joystick.on(cc.Node.EventType.TOUCH_END, function (e) {
            this.Joystick.setPosition(cc.v2(0, 0));
            this.dir = cc.v2(0, 0);
        }, this);

        this.Joystick.on(cc.Node.EventType.TOUCH_CANCEL, function (e) {
            this.Joystick.setPosition(cc.v2(0, 0));
            this.dir = cc.v2(0, 0);
        }, this);
    }
}
